﻿

/*simple command to read a snes rom into a file buffer with a dialog box
 * Gareth Williams
 */

using System;
using System.IO;
using VuzixSample.model.snes;
namespace VuzixSample.controller.snes
{
    class LoadRomCommand : ICommand
    {
        private string filename = "Content/Star Fox.smc";

        public void Execute()
        {
            Execute(null);
        }
        public void Execute(object _rom)
        {
            SnesRom rom = _rom as SnesRom;
            //string filename = createOpenFileDialog();
            
            if (filename.Length > 0)
            {
                if (rom != null)
                {
                    rom.Clear();
                }
                else
                {
                    rom = new SnesRom();
                }

                rom.romData = ReadFile(filename);
                
                romLoaded(this, new RomLoadedArgs(rom));
            }
        }
        /*
        private string createOpenFileDialog()
        {
            Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();
            dialog.DefaultExt = ".smc";
            dialog.Filter = "SMC Headered SNES Rom (.smc)|*.smc";

            Nullable<bool> result = dialog.ShowDialog();

            string filename = "";
            if (true == result) filename = dialog.FileName;

            return filename;
        }
        */
        private static byte[] ReadFile(string fromPath)
        {
            byte[] buffer;
            FileStream fileStream = new FileStream(fromPath, FileMode.Open, FileAccess.Read);

            try
            {
                int length = (int)fileStream.Length;
                buffer = new byte[length];
                int count;
                int sum = 0;

                while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                {
                    sum += count;
                }
            }
            finally
            {
                fileStream.Close();
            }

            return buffer;
        }
        /*
        public bool CanExecute(object parameter)
        {
            return parameter != null;
        }
        */
        public event EventHandler romLoaded;
    }

    //helper class

    public class RomLoadedArgs : EventArgs
    {
        public SnesRom rom;

        public RomLoadedArgs(SnesRom rom)
        {
            this.rom = rom;
        }
    }
}
